import { ref } from 'vue'
import { getBaseListApi, getBaseDetailApi, type BaseInfo, type BaseDetailResponse } from '~/server/baseApi'
import { PageQuery } from '~/types/global'

/**
 * 基地管理相关的组合式函数
 */
export const useBase = () => {
    const loading = ref(false)
    const loadingDetails = ref(false)
    const baseList = ref<BaseInfo[]>([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)

    /**
     * 获取基地列表
     * @param params 分页参数
     */
    const fetchBaseList = async (params?: Partial<PageQuery & { keyword?: string }>) => {
        try {
            loading.value = true
            const queryParams: PageQuery & { keyword?: string } = {
                page: params?.page || currentPage.value,
                limit: params?.limit || pageSize.value,
                ...params
            }

            const data = await getBaseListApi(queryParams)
            baseList.value = data.list || []
            total.value = data.total || 0

            // 列表数据已包含关键字段，无需补充详情

            return data
        } catch (error) {
            console.error('获取基地列表失败:', error)
            // 如果是认证错误，提供更友好的错误信息
            if (error && (error.toString().includes('401') || error.toString().includes('402'))) {
                throw new Error('需要登录才能访问基地信息')
            }
            throw error
        } finally {
            loading.value = false
        }
    }

    // 已移除详情补全逻辑：列表字段已完整，无需额外请求

    /**
     * 获取基地详情
     * @param id 基地ID
     */
    const fetchBaseDetail = async (id: number): Promise<BaseDetailResponse> => {
        try {
            loading.value = true
            const data = await getBaseDetailApi(id)
            return data
        } catch (error) {
            console.error('获取基地详情失败:', error)
            // 如果是认证错误，提供更友好的错误信息
            if (error && (error.toString().includes('401') || error.toString().includes('402'))) {
                throw new Error('需要登录才能查看基地详情')
            }
            throw error
        } finally {
            loading.value = false
        }
    }

    /**
     * 刷新基地列表
     */
    const refreshBaseList = () => {
        return fetchBaseList()
    }

    /**
     * 分页变化处理
     * @param page 页码
     * @param size 每页数量
     */
    const handlePageChange = (page: number, size?: number) => {
        currentPage.value = page
        if (size) {
            pageSize.value = size
        }
        return fetchBaseList()
    }

    return {
        // 状态
        loading,
        loadingDetails,
        baseList,
        total,
        currentPage,
        pageSize,

        // 方法
        fetchBaseList,
        fetchBaseDetail,
        refreshBaseList,
        handlePageChange
    }
}
